#!/usr/bin/env python3
"""
钉钉智能助手系统完整性检查脚本
"""

import os
import sys
import logging
from pathlib import Path

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("SystemCheck")

def check_file_structure():
    """检查文件结构完整性"""
    logger.info("检查文件结构完整性...")
    
    required_files = [
        "README.md",
        "USER_MANUAL.md", 
        "PROJECT_STRUCTURE.md",
        "requirements.txt",
        "start_system.py",
        ".env.example",
        "langgraph_supervisor.py",
        "optimization_solution.py",
        "dingding/Agents.py",
        "dingding/DingWebHook.py",
        "dingding/dingtalk_agent.py",
        "dingding/memory_manager.py",
        "knowledge_base/__init__.py",
        "knowledge_base/knowledge_agent.py",
        "knowledge_base/prepare_knowledge_base.py",
        "knowledge_base/validate_knowledge_base.py",
        "text2sql/text2sql_tools.py",
        "text2sql/insert_ddl_to_milvus.py",
        "text2sql/insert_q2sql_to_milvus.py",
        "text2sql/insert_desc_to_milvus.py"
    ]
    
    missing_files = []
    for file_path in required_files:
        if not Path(file_path).exists():
            missing_files.append(file_path)
    
    if missing_files:
        logger.error(f"缺少必要文件: {missing_files}")
        return False
    
    logger.info("文件结构检查通过")
    return True

def check_import_structure():
    """检查导入结构"""
    logger.info("检查导入结构...")
    
    try:
        # 检查核心模块导入
        from dingding.Agents import AgentClass
        logger.info("✅ AgentClass导入成功")
        
        from langgraph_supervisor import create_supervisor
        logger.info("✅ LangGraph supervisor导入成功")
        
        from optimization_solution import get_optimized_supervisor
        logger.info("✅ 优化方案导入成功")
        
        from knowledge_base.knowledge_agent import KnowledgeAgent
        logger.info("✅ Knowledge Agent导入成功")
        
        from dingding.dingtalk_agent import DingTalkAgent
        logger.info("✅ DingTalk Agent导入成功")
        
        return True
        
    except ImportError as e:
        logger.error(f"导入失败: {e}")
        return False

def check_environment_template():
    """检查环境配置模板"""
    logger.info("检查环境配置模板...")
    
    if not Path(".env.example").exists():
        logger.error("缺少.env.example文件")
        return False
    
    with open(".env.example", "r", encoding="utf-8") as f:
        content = f.read()
    
    required_vars = [
        "OPENAI_API_KEY",
        "MYSQL_HOST",
        "MYSQL_USER",
        "MYSQL_PASSWORD", 
        "MYSQL_DATABASE",
        "MILVUS_HOST",
        "REDIS_HOST",
        "DINGTALK_APP_KEY"
    ]
    
    missing_vars = []
    for var in required_vars:
        if var not in content:
            missing_vars.append(var)
    
    if missing_vars:
        logger.error(f".env.example缺少配置项: {missing_vars}")
        return False
    
    logger.info("环境配置模板检查通过")
    return True

def check_documentation():
    """检查文档完整性"""
    logger.info("检查文档完整性...")
    
    docs = {
        "README.md": ["快速开始", "技术架构", "核心功能"],
        "USER_MANUAL.md": ["系统概述", "核心功能", "系统启动"],
        "PROJECT_STRUCTURE.md": ["目录结构", "核心模块", "工作流程"]
    }
    
    for doc_file, required_sections in docs.items():
        if not Path(doc_file).exists():
            logger.error(f"缺少文档: {doc_file}")
            return False
        
        with open(doc_file, "r", encoding="utf-8") as f:
            content = f.read()
        
        missing_sections = []
        for section in required_sections:
            if section not in content:
                missing_sections.append(section)
        
        if missing_sections:
            logger.error(f"{doc_file}缺少章节: {missing_sections}")
            return False
    
    logger.info("文档完整性检查通过")
    return True

def check_agent_integration():
    """检查智能体集成"""
    logger.info("检查智能体集成...")
    
    try:
        # 检查四智能体架构
        from dingding.Agents import AgentClass
        agent = AgentClass()
        
        # 检查supervisor配置
        if not hasattr(agent, 'workflow') or not agent.workflow:
            logger.error("Supervisor workflow未正确初始化")
            return False
        
        # 检查路由映射
        from langgraph_supervisor import create_supervisor
        test_supervisor = create_supervisor([])
        
        logger.info("智能体集成检查通过")
        return True
        
    except Exception as e:
        logger.error(f"智能体集成检查失败: {e}")
        return False

def generate_system_report():
    """生成系统报告"""
    logger.info("生成系统报告...")
    
    report = """
# 钉钉智能助手系统检查报告

## 系统状态
- 文件结构: ✅ 完整
- 导入结构: ✅ 正常
- 环境配置: ✅ 完整
- 文档完整性: ✅ 完整
- 智能体集成: ✅ 正常

## 核心功能
1. **电影数据库查询** (Text2SQL Agent)
   - 基于MySQL Sakila数据库
   - 支持自然语言查询转SQL
   - 票房分析、演员查询、库存管理

2. **钉钉办公功能** (DingTalk Agent)
   - 待办事项管理
   - 日程安排
   - 联系人查询

3. **企业知识检索** (Knowledge Agent)
   - 政策文档查询
   - 技术手册检索
   - FAQ问答

4. **智能路由协调** (Supervisor)
   - 多层路由机制
   - 查询重写优化
   - 上下文管理

## 技术架构
- **LangGraph**: 多智能体工作流编排
- **LangChain**: AI应用开发框架
- **OpenAI GPT**: 大语言模型
- **Milvus**: 向量数据库
- **MySQL**: Sakila电影数据库
- **Redis**: 缓存和会话管理

## 启动方式
```bash
# 1. 配置环境
cp .env.example .env
# 编辑.env文件

# 2. 安装依赖
pip install -r requirements.txt

# 3. 启动系统
python start_system.py
```

## 系统就绪状态: ✅ 完全就绪
"""
    
    with open("SYSTEM_REPORT.md", "w", encoding="utf-8") as f:
        f.write(report)
    
    logger.info("系统报告已生成: SYSTEM_REPORT.md")

def main():
    """主检查函数"""
    print("🔍 钉钉智能助手系统完整性检查")
    print("=" * 60)
    
    checks = [
        ("文件结构", check_file_structure),
        ("导入结构", check_import_structure),
        ("环境配置", check_environment_template),
        ("文档完整性", check_documentation),
        ("智能体集成", check_agent_integration)
    ]
    
    results = []
    for check_name, check_func in checks:
        print(f"\n🔍 检查{check_name}...")
        try:
            result = check_func()
            results.append((check_name, result))
            status = "✅ 通过" if result else "❌ 失败"
            print(f"   {status}")
        except Exception as e:
            results.append((check_name, False))
            print(f"   ❌ 异常: {e}")
    
    # 统计结果
    total_checks = len(results)
    passed_checks = sum(1 for _, passed in results if passed)
    
    print("\n" + "=" * 60)
    print("📊 系统检查结果")
    print("=" * 60)
    
    for check_name, passed in results:
        status = "✅ 通过" if passed else "❌ 失败"
        print(f"   {check_name}: {status}")
    
    print(f"\n🎯 总体结果:")
    print(f"   总检查数: {total_checks}")
    print(f"   通过数: {passed_checks}")
    print(f"   成功率: {passed_checks/total_checks:.1%}")
    
    if passed_checks == total_checks:
        print("   状态: 🎉 系统完全就绪")
        generate_system_report()
        success = True
    elif passed_checks >= total_checks * 0.8:
        print("   状态: ⚠️ 系统基本就绪，有少量问题")
        success = True
    else:
        print("   状态: ❌ 系统存在重要问题")
        success = False
    
    print(f"\n📋 下一步:")
    if success:
        print("   1. 配置.env文件")
        print("   2. 初始化数据库")
        print("   3. 运行 python start_system.py")
    else:
        print("   1. 解决上述检查失败的问题")
        print("   2. 重新运行系统检查")
    
    return success

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
